import React, { useState } from 'react';
import { Card, Form, Input, Select, DatePicker, Button, Table, Space, Tag, message } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import './Index.scss';

const { RangePicker } = DatePicker;

interface OrderType {
  key: string;
  orderNo: string;
  customerName: string;
  amount: number;
  status: 'pending' | 'processing' | 'completed' | 'cancelled';
  paymentMethod: string;
  createTime: string;
}

// 模拟订单数据
const generateFakeOrders = (count: number): OrderType[] => {
  const status: OrderType['status'][] = ['pending', 'processing', 'completed', 'cancelled'];
  const paymentMethods = ['支付宝', '微信支付', '银行卡'];
  
  return Array.from({ length: count }, (_, index) => ({
    key: `${index + 1}`,
    orderNo: `ORD${String(index + 1).padStart(6, '0')}`,
    customerName: `客户${index + 1}`,
    amount: Math.floor(Math.random() * 10000) + 100,
    status: status[Math.floor(Math.random() * status.length)],
    paymentMethod: paymentMethods[Math.floor(Math.random() * paymentMethods.length)],
    createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toLocaleString()
  }));
};

const OrderList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<OrderType[]>(() => generateFakeOrders(100));
  const [filteredData, setFilteredData] = useState<OrderType[]>(data);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: data.length,
    showSizeChanger: true,
    showQuickJumper: true
  });

  const statusColors = {
    pending: 'gold',
    processing: 'blue',
    completed: 'green',
    cancelled: 'red'
  };

  const statusText = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  };

  const columns: TableProps<OrderType>['columns'] = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 150,
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
      sorter: (a, b) => a.amount - b.amount,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: keyof typeof statusColors) => (
        <Tag color={statusColors[status]}>
          {statusText[status]}
        </Tag>
      ),
      filters: Object.entries(statusText).map(([key, text]) => ({
        text,
        value: key,
      })),
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link">查看详情</Button>
          <Button type="link" disabled={record.status === 'completed'}>修改</Button>
          <Button type="link" danger disabled={record.status === 'cancelled'}>
            取消订单
          </Button>
        </Space>
      ),
    },
  ];

  const handleSearch = async (values: any) => {
    setLoading(true);
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      let filtered = [...data];

      if (values.orderNo) {
        filtered = filtered.filter(item => 
          item.orderNo.toLowerCase().includes(values.orderNo.toLowerCase())
        );
      }

      if (values.customerName) {
        filtered = filtered.filter(item =>
          item.customerName.includes(values.customerName)
        );
      }

      if (values.status) {
        filtered = filtered.filter(item => item.status === values.status);
      }

      if (values.dateRange) {
        const [start, end] = values.dateRange;
        filtered = filtered.filter(item => {
          const createTime = new Date(item.createTime).getTime();
          return createTime >= start.valueOf() && createTime <= end.valueOf();
        });
      }

      setFilteredData(filtered);
      setPagination(prev => ({
        ...prev,
        current: 1,
        total: filtered.length
      }));
      message.success('查询成功');
    } catch (error) {
      message.error('查询失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    setFilteredData(data);
    setPagination(prev => ({
      ...prev,
      current: 1,
      total: data.length
    }));
  };

  const handleTableChange: TableProps<OrderType>['onChange'] = (newPagination) => {
    // @ts-expect-error
    setPagination(prev => ({
      ...prev,
      ...newPagination,
    }));
  };

  return (
    <div className="order-list">
      <Card className="search-card">
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          className="search-form"
        >
          <Form.Item name="orderNo" label="订单编号">
            <Input placeholder="请输入订单编号" allowClear />
          </Form.Item>
          
          <Form.Item name="customerName" label="客户名称">
            <Input placeholder="请输入客户名称" allowClear />
          </Form.Item>
          
          <Form.Item name="status" label="订单状态">
            <Select
              placeholder="请选择状态"
              allowClear
              style={{ width: 120 }}
              options={Object.entries(statusText).map(([key, text]) => ({
                value: key,
                label: text,
              }))}
            />
          </Form.Item>

          <Form.Item name="dateRange" label="创建时间">
            <RangePicker showTime />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card className="table-card">
        <Table
          columns={columns}
          dataSource={filteredData}
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
          scroll={{ x: 1300 }}
        />
      </Card>
    </div>
  );
};

export default OrderList; 